﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Security.Cryptography;

namespace ActivityTrackingLog.Utils
{
    public static class TypeExtentions
    {
        public static string ToLowerTrimSafe(this string str)
        {
            return string.IsNullOrEmpty(str) ? str : str.ToLower().Trim();
        }

        public static bool CompareIgnoreCase(this string str, string strCompareTo)
        {
            if (null == str && null == strCompareTo)
                return true;

            if (null == str || null == strCompareTo)
                return false;

            return String.Compare(str.Trim().ToLower(), strCompareTo.Trim().ToLower(), true) == 0;
        }

        public static T Convert<T>(this string input, T defaultValue)
        {
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null)
            {
                try
                {
                    return (T)converter.ConvertFromString(input);
                }
                catch (FormatException) { }
                catch (Exception ex)
                {
                    if (null == ex.InnerException || !(ex.InnerException is FormatException))
                        throw;
                }
            }
            return defaultValue;
        }

        public static string ToSha256Base64(this string originalString)
        {
            // The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] dataArray = encoding.GetBytes(originalString);

            using (SHA256 shaM = new SHA256Managed())
            {
                var hash = shaM.ComputeHash(dataArray);
                return System.Convert.ToBase64String(hash);
            }
        }

        public static string GetTypeName(this Type t)
        {
            if (t.IsGenericType)
            {
                Type g = t.GetGenericTypeDefinition();
                return g.Name.Remove(g.Name.IndexOf('`'));
            }

            return t.Name;
        }

        public static T[] SubArray<T>(this T[] data, int index, int length)
        {
            T[] result = new T[length];
            Array.Copy(data, index, result, 0, length);
            return result;
        }
    }
}
